/**
 * @description Export All Service Api
 * apiMap参数
 *{
 *  type: 'post',
    isPathParameter: true, //路径参数拼接 url + /${methodUrl}
    url: 'resource/protection-target',
    server: 'bimServer',
    loading: true,
 *}
 */

import request from '@/utils/request'
import axios from 'axios'
import { Loading } from '@ued_fpi/element-ui'

import config from '@config'

const serviceFiles = require.context('./modules', false, /\.js$/)

const serviceCombine = {}
const service = {}
const CancelToken = axios.CancelToken

serviceFiles.keys().forEach(key => {
    const filename = key.replace(/(\.\/|\.js)/g, '')
    serviceCombine[filename] = serviceFiles(key).default
})

let loadingInstance = null

for (const key in serviceCombine) {
    service[key] = {}
    const apiMap = serviceCombine[key]
    const { defaultServer, servers } = config
    for (const methodName in apiMap) {
        service[key][methodName] = async (data, methodUrl = '', _this) => {
            const apiData = apiMap[methodName]
            const url = apiData.isPathParameter
                ? apiData.url.replace(/^\//, '') + `/${methodUrl}`
                : methodUrl || apiData.url.replace(/^\//, '')
            const serverFlag = /^http/.test(url)

            let response = null

            let server = ''
            if (!serverFlag) {
                server = apiData.server ? servers[apiData.server] : defaultServer
            }

            if (apiData.loading) {
                loadingInstance = Loading.service({})
            }

            const requestConfig = {
                method: apiData.type || 'get',
                url: server + url,
            }
            const dataName = requestConfig.method.toLocaleUpperCase() === 'GET' ? 'params' : 'data'
            requestConfig[dataName] = data
            // 取消请求方法
            // data() {
            //     return {
            //       cancelAjax: null
            //     }
            //  }
            // post(){
            //  if (typeof this.cancelAjax === 'function') {
            //     this.cancelAjax()
            //   }
            //  this.$http.app.info({}, 'url', this).then((res=>{})
            // }
            if (_this) {
                requestConfig.cancelToken = new CancelToken(function executor(c) {
                    _this.cancelAjax = c
                })
            }
            try {
                response = await request(requestConfig)
                if (_this) {
                    _this.cancelAjax = null
                }
                if (apiData.loading) {
                    loadingInstance.close()
                }
                return response
            } catch (err) {
                if (_this) {
                    _this.cancelAjax = null
                }
                if (apiData.loading) {
                    loadingInstance.close()
                }
                return Promise.reject(err)
            }
        }
    }
}

export default service
